package cn.lingyangwl.agile.msg.push.service.impl;

import cn.lingyangwl.agile.model.*;
import cn.lingyangwl.agile.model.constants.*;
import cn.lingyangwl.agile.msg.push.assembly.*;
import cn.lingyangwl.agile.msg.push.mapper.*;
import cn.lingyangwl.agile.msg.push.model.entity.*;
import cn.lingyangwl.agile.msg.push.model.rqrs.field.*;
import cn.lingyangwl.agile.msg.push.service.*;
import cn.lingyangwl.agile.tenant.core.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 消息字段库
 *
 * @author shenguangyang
 */
@Slf4j
@Service
public class FieldLibraryServiceImpl extends ServiceImpl<FieldLibraryMapper, FieldLibrary>
    implements IService<FieldLibrary>, FieldLibraryService {

    @Resource
    private FieldLibraryAssembly fieldLibraryAssembly;
    
    @Override
    @Tenant(level = DataIsolateLevel.MGT)
    public List<FieldLibraryResp> listField(String keyWord) {
        LambdaQueryWrapper<FieldLibrary> lqw = FieldLibrary.lqw()
            .like(StringUtils.isNotEmpty(keyWord), FieldLibrary::getFieldKey, keyWord)
            .or()
            .like(StringUtils.isNotEmpty(keyWord), FieldLibrary::getFieldName, keyWord)
            .orderByDesc(BasePlusPO::getCreatedAt);
        return this.list(lqw).stream()
    	        .map(fieldLibraryAssembly::toFieldLibraryResp).collect(Collectors.toList());
    }

    @Override
    @Tenant(level = DataIsolateLevel.MGT)
    public boolean saveField(FieldLibrarySaveReq req) {
        FieldLibrary entity = fieldLibraryAssembly.toFieldLibrary(req);
        checkWrite(entity);
    	return this.save(entity);
    }

    @Override
    @Tenant(level = DataIsolateLevel.MGT)
    public boolean updateField(FieldLibrarySaveReq req) {
        FieldLibrary entity = fieldLibraryAssembly.toFieldLibrary(req);
        checkWrite(entity);
    	return this.updateById(entity);
    }

    public void checkWrite(FieldLibrary req) {
        LambdaQueryWrapper<FieldLibrary> lqw = FieldLibrary.lqw()
            .ne(Objects.nonNull(req.getId()), FieldLibrary::getId, req.getId())
            .eq(StringUtils.isNotEmpty(req.getFieldKey()), FieldLibrary::getFieldKey, req.getFieldKey());
        if (this.count(lqw) > 0) {
            throw new BizException("字段Key [{}] 已存在", req.getFieldKey());
        }
    }

    @Override
    @Tenant(level = DataIsolateLevel.MGT)
    public boolean batchDeleteField(List<Long> ids) {
    	return this.removeByIds(ids);
    }
}
